# -*- coding: utf-8 -*-
import json
import requests
import os
import signal
import time
import serial
import threading
import base64
import redis
import traceback


def signal_handler(signal, frame):

    print('program exit')
    try:
        ser.close()
        gpsfile.close()
    except:
        pass
    exit()
signal.signal(signal.SIGINT, signal_handler)



def rtkTest(conf):
    try:
        url = 'http://'+conf['rtkserver']
        res = requests.get(url)
        if res.status_code==200:

            data = json.loads(res.text)
            timeArray = time.strptime(data['data']['update_time'], "%Y-%m-%d %H:%M:%S")
            itime = int(time.mktime(timeArray))
            if int(time.time()) -itime >180 :
                return False
            else:
                print(data['data']['update_time'],"RTK OK \r\n",)

    except:
#        traceback.print_exc()
        print("GET ERR\r\n")
        return False
    return True

def roverGps(redisc):
    try:
        gps = redisc.get('gps')
        # print(gps)
        if gps is not None:
            return True
            gpsdata = json.loads(gps)
            if isinstance(gpsdata,dict):
                return True

        return None
    except:
        return None    

def testRun(conf,redisc):

    if conf['gpstype']=="2":
        while True:
            print("rtk ...\n")
            time.sleep(20)
            if redisc.get('rtkdata')==None:
                os.system('/home/wwwroot/pavgps/control.sh stop')
                print("restart rtk ...\n")
                os.system('nohup /home/wwwroot/pavgps/control.sh start >/dev/null 2>&1 &')
                time.sleep(3)

    if conf['gpstype']=='1':
        print("rover\r\n")
        gpsErrNum = 0
        while True:
            time.sleep(20)

            data = roverGps(redisc)
            print("\r\ngpsErrNum", gpsErrNum)
            if data is None:
                gpsErrNum=gpsErrNum+1
            else:
                gpsErrNum=0

            if gpsErrNum>2:
                os.system('/home/wwwroot/pavgps/control.sh stop')
                print("restart rover ...\n")
                os.system('nohup /home/wwwroot/pavgps/control.sh start >/dev/null 2>&1 &')
                time.sleep(3)
                gpsErrNum=0
            print(data)


if __name__=='__main__':

    dirname, filename = os.path.split(os.path.abspath(__file__)) 
    redisc = redis.Redis(host='127.0.0.1',port=6379)
    file = dirname+"/config.json"
    
    conf = []
    if os.path.isfile(file)==True:
        f=open(file)
        s=f.read()
        conf= json.loads(s)

    
    testRun(conf,redisc)

